"""
Copyright 2008 Olivier Belanger

This file is part of Ounk.

Ounk is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Ounk is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Ounk.  If not, see <http://www.gnu.org/licenses/>.
"""

import threading, time
from types import ListType

class MyTimer(threading.Thread):
    def __init__(self, time, function, pattern, *args):
        threading.Thread.__init__(self)
        self.args = args
        self.t = time
        self.currentTime = 0
        self.function = function
        self.pattern = pattern
        self.terminated = False
        self.next = 0
        self.count = 1
        self.ok = False
        self.bar = 0
        
    def run(self):
        while not self.terminated:
            if self.ok:
                if self.count == 1:
                    self.function(*self.args)
                self.count += 1
                if self.count > self.pattern[self.next]:
                    self.count = 1
                    self.next = (self.next + 1) % len(self.pattern)
                    if self.next == 0:
                        self.bar += 1
            self.currentTime += self.t              
            time.sleep(self.t)
        print "thread terminated"    

    def play(self, state=True):
        self.ok = state
        
    def changePattern(self, pattern):
        """Assigns a new pattern to a pattern objet.

pattern = [list_ticks_duration]

--- PARAMETERS ---

pattern : List of ticks duration.        
"""        
        if type(pattern) != ListType: pattern = [pattern]
        self.pattern = pattern
        self.next = 0
        self.count = 1

    def changeTime(self, time):
        """Changes the time interval of a pattern objet.
     
time = time_interval_secs

--- PARAMETERS ---

time : Time interval, in seconds, between clocker calls.
"""
        self.t = time

    def getBeat(self):
        """Returns the current beat of the pattern."""
        return self.next + 1

    def getBar(self):
        """Return the current bar of the pattern."""
        return self.bar

    def getTime(self):
        """Returns the current time of the pattern."""
        return self.currentTime
        
    def stop(self):
        self.terminated = True

